
module add3(in,out);
input [3:0] in;
output [3:0] out;
reg [3:0] out;

always @ (in)
	case (in)
	  4'b0000: out <= 4'b0000;
	  4'b0001: out <= 4'b0001;
	  4'b0010: out <= 4'b0010;
	  4'b0011: out <= 4'b0011;
	  4'b0100: out <= 4'b0100;
	  4'b0101: out <= 4'b1000;
	  4'b0110: out <= 4'b1001;
	  4'b0111: out <= 4'b1010;
	  4'b1000: out <= 4'b1011;
	  4'b1001: out <= 4'b1100;
	  default: out <= 4'b0000;
	endcase
endmodule


module binary_to_BCD(A,ONES,TENS,HUNDREDS);
   input [7:0] A;
   output [3:0] ONES, TENS;
   output [1:0] HUNDREDS;
   wire [3:0] c1,c2,c3,c4,c5,c6,c7;
   wire [3:0] d1,d2,d3,d4,d5,d6,d7;
   
   assign d1  = {1'b0,A[7:5]};
   assign d2  = {c1[2:0],A[4]};
   assign d3  = {c2[2:0],A[3]};
   assign d4  = {c3[2:0],A[2]};
   assign d5  = {c4[2:0],A[1]};
   assign d6  = {1'b0,c1[3],c2[3],c3[3]};
   assign d7  = {c6[2:0],c4[3]};
   
   add3 m1(d1,c1);
   add3 m2(d2,c2);
   add3 m3(d3,c3);
   add3 m4(d4,c4);
   add3 m5(d5,c5);
   add3 m6(d6,c6);
   add3 m7(d7,c7);
   
   assign ONES = {c5[2:0],A[0]};
   assign TENS = {c7[2:0],c5[3]};
   assign HUNDREDS = {c6[3],c7[3]};
endmodule


module counter(input CK12, 
			   input TXE_, 
			   output WR, 
			   output [7:0] LED, 
			   output [7:0] USBD);
   
   reg wrf 	= 0;
   reg [2:0] k = 0;
   
   wire [3:0] ones;
   wire [3:0] tens;
   wire [1:0] hund;

   reg [3:0] ob  = 4'b0000;
   reg [3:0] tb  = 4'b0000;
   reg [1:0] hb  = 1'b0;
   
   reg [7:0] count = 8'b00000000;
   reg [7:0] sbyte = 8'b00000000;

   
   always @(posedge CK12)
	 begin
		
		if (TXE_ == 0 && wrf == 1)
		  begin
			 wrf 	= 0;
		  end
      
		// If we've already lowered the strobe, latch the data
		else if (wrf == 0)
		  begin
			 case(k)
			   0: sbyte  = hb;
			   1: sbyte  = tb;
			   2: sbyte  = ob;
			   3: sbyte  = 8'b00001010; //newline
			 endcase
			   
			 if (k < 3)
			   begin
				  k 	 = k + 1;
				  sbyte  = sbyte + 8'b00110000;
			   end

			 else
			   begin
				  count  = count + 1;
				  hb 	<= hund;
				  tb 	<= tens;
				  ob 	<= ones;				  
				  k 	 = 0;
			   end
			 
			 wrf 		 = 1;

		  end		
	 end

   binary_to_BCD bcd (count, ones, tens, hund);
   
   assign WR 			 = wrf;
   assign USBD 			 = sbyte;
   assign LED 			 = count;
      
endmodule // counter
